export enum EventType {
    OPEN = 'onopen',
    MESSAGE = 'onmessage',
    ERROR = 'onerror',
    CLOSE = "onclose"
}


export class SocketHelper {
    private ws: WebSocket;
    public constructor(url: string) {
        this.ws = new WebSocket(url);
    }


    public onEvent(et: EventType, handle: (() => void) | ((...msg: any) => void)) {
        this.ws[et] = handle;
    }

    public close(): void {
        this.ws.close();
    }

    public sendMsg(msg: string): void {
        this.ws.send(msg);
    }
}


export type Handler = (msgObj: { type: number }) => void

export interface IHandles {
    [type: number]: Handler[]
}


export enum HandlerType {
    FLUSH_MESSAGE = 1,
    FLUSH_ONLINE = 2,
    FLUSH_ONLINE_LIST = 3
}

export class MessageHandler {
    private handlers: IHandles

    constructor() {
        this.handlers = {}
    }

    public registeEvent(type: HandlerType, handlerFunc: Handler): void {
        let hs = this.handlers[type]
        if (!hs) {
            hs = []
            this.handlers[type] = hs
        }
        hs.push(handlerFunc);
    }

    public handle(msgObj: { type: number }) {
        const type = msgObj.type;
        if (!type) {
            return;
        }
        const h = this.handlers[type];
        if (h) {
            for (let i = 0; i < h.length; i++) {
                h[i](msgObj)
            }
        }

    }
}
